<!-- 品类管理 -->
<template>
  <div>
    <CommonSearch @search="filterQuery" @reset="reset">
      <el-col :span="8">
        <el-form-item label="品类名称">
          <el-input
            v-model="queryParams.condition.name"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </CommonSearch>

    <el-row class="cardMiniBar">
      <el-col :span="24">
        <div class="fr">
          <el-button @click="add" size="small">新增</el-button>
          <el-button @click="batchImport" size="small">批量导入</el-button>
          <el-button @click="handlerDelete" size="small">批量删除</el-button>
        </div>
      </el-col>
    </el-row>

    <div class="cardBody">
      <el-tree
        ref="tree"
        :data="tableList"
        :props="defaultProps"
        show-checkbox
        :default-expand-all="false"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        style="max-height: 450px; overflow: auto"
      >
        <div class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>

          <span>
            <el-button type="text" size="mini" @click="add(node, data)" v-if="node.level <= 2">
              新增
            </el-button>
            <el-button type="text" size="mini" @click="edit(node, data)">
              修改
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="handlerDelete(node, data)"
            >
              删除
            </el-button>
          </span>
        </div>
      </el-tree>
    </div>

    <edu-dialog
      :title.sync="dialogConfig.title"
      :visible.sync="dialogConfig.showDialog"
      @close="closeDialog(dialogConfig)"
    >
      <el-form
        ref="dialogForm"
        :model="dialogConfig.formData"
        :rules="dialogConfig.action === 'view' ? {} : dialogConfig.rules"
        label-width="230px"
        size="small"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="品类名称" prop="name">
              <el-input v-model="dialogConfig.formData.name" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="dialogConfig.formData.sort"
                controls-position="right"
                :min="0"
                :step="1"
                :step-strictly="true"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="buttons" v-if="dialogConfig.action !== 'view'">
        <template>
          <el-button @click="closeDialog(dialogConfig)"> 取消 </el-button>
          <el-button type="primary" @click="handlerSubmit"> 提交 </el-button>
        </template>
      </span>
      <span slot="buttons" v-else>
        <template>
          <el-button @click="closeDialog(dialogConfig)">返回</el-button>
        </template>
      </span>
    </edu-dialog>

    <!-- 批量导入 -->
    <BatchImport
      ref="batchImport"
      downloadTplUrl="com.iss.edu.service.business.vo.farm.ImportProduceCategoryVo"
      action="/nongmao/nb-pc/1.0.1/ProduceCategoryService/importProduceCategory"
      @uploadDone="uploadDone"
      @done="query"
    />
  </div>
</template>

<script>
import utils from "@/utils";
import mixins from "@/mixins";

import {
  queryProduceCategoryTree,
  addProduceCategory,
  deleteProduceCategory,
  updateProduceCategory,
} from "@/api/market";

const formData = {
  name: "",
  sort: 0,
};

export default {
  mixins: [mixins],
  data() {
    return {
      defaultProps: {
        children: "subProduceCategoryList",
        label: "name",
      },
      queryParams: {
        condition: {},
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      tableList: [],
      dialogConfig: {
        title: "",
        showDialog: false,
        action: "add",
        formData: {},
        rules: {
          name: [
            {
              required: true,
              validator: this.checkName,
              trigger: "blur",
            },
          ],
        },
        fileList: [],
      },
      ids: [],
    };
  },
  created() {
    this.initOptions();
  },
  methods: {
    checkName(rule, value, callback) {
      if (!value) {
        callback(new Error("此项必填！"));
      } else if (value.length > 100) {
        callback(new Error("超出字数限制100"));
      } else {
        callback();
      }
    },
    async initOptions() {},
    // 查询
    async query() {
      let { returnObj } = await queryProduceCategoryTree(this.queryParams);
      this.tableList = returnObj;
    },
    // 重置
    reset() {
      for (var key in this.queryParams.condition) {
        this.queryParams.condition[key] = "";
      }
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.query();
    },
    filterQuery() {
      this.$refs.tree.filter(this.queryParams.condition.name);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    closeDialog(dialog) {
      dialog.showDialog = false;
      this.$refs["dialogForm"].resetFields();
    },
    openDialog(dialog) {
      dialog.showDialog = true;
    },
    // 新增
    add(node, row) {
      this.dialogConfig.title = "新增";
      this.dialogConfig.action = "add";

      if (row) {
        formData.parentId = row.id;
      } else {
        formData.parentId = -1;
      }
      this.dialogConfig.formData = utils.clone(formData);

      this.openDialog(this.dialogConfig);
    },
    // 修改
    async edit(node, row) {
      this.dialogConfig.title = "编辑";
      this.dialogConfig.action = "edit";

      this.dialogConfig.formData = utils.clone(row);

      this.openDialog(this.dialogConfig);
    },
    // 保存提交
    handlerSubmit() {
      let params = {
        ...this.dialogConfig.formData,
      };
      this.$refs["dialogForm"].validate((valid) => {
        if (valid) {
          if (this.dialogConfig.action == "add") {
            addProduceCategory(params).then((res) => {
              this.$message({
                type: "success",
                message: "成功",
              });
              this.closeDialog(this.dialogConfig);
              this.query();
            });
          } else {
            updateProduceCategory(params).then((res) => {
              this.$message({
                type: "success",
                message: "成功",
              });
              this.closeDialog(this.dialogConfig);
              this.query();
            });
          }
        }
      });
    },
    // 查看
    view() {
      this.dialogConfig.title = "查看";
      this.dialogConfig.action = "view";
      this.openDialog(this.dialogConfig);
    },
    // 批量导入
    async batchImport() {
      this.$refs.batchImport.open();
    },
    uploadDone(data) {
      let msg = [];
      data.map((item, index) => {
        if (item.checkResult) {
          msg.push(`第${index + 1}行 ${item.checkResult}`);
        }
      });

      this.$alert(msg.join("<br/>"), "警告", {
        dangerouslyUseHTMLString: true,
      });
    },
    getIds(row) {
      this.ids.push(row.id);
      if (row.subProduceCategoryList && row.subProduceCategoryList.length > 0) {
        row.subProduceCategoryList.map((item) => {
          this.getIds(item);
        });
      }
    },
    // 删除
    async handlerDelete(node, row) {
      this.ids = [];
      if (row) {
        this.getIds(row);
      } else {
        let ids = this.$refs.tree.getCheckedNodes();
        this.ids = ids.map((item) => item.id);
      }

      if (this.ids.length <= 0) {
        this.$message({
          type: "warning",
          message: "请勾选数据",
        });
        return;
      }

      this.$confirm(`确认删除?`).then(() => {
        deleteProduceCategory(this.ids).then((res) => {
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.query();
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
